#!/usr/bin/env python

import sys

class Book:
  def __init__(self, isbn):
    self.isbn = isbn
    # Tyler's code has an unnecessary 13th ISBN digit. Drop it.
    self.id = self.isbn[0:12]
    self.amazon_price = None
    self.uw_price = None

  def profit(self):
    return self.uw_price - self.amazon_price

  def roi(self):
    return self.profit() / self.amazon_price

  def utility(self):
    """ Returns a floating-point number. A higher value means the book is
    more desirable for us.
    """
    # We consider each book to have a base labor cost of $8
    cost = self.amazon_price + 8
    return self.uw_price / cost

  def mergeFrom(self, other):
    assert self.id == other.id
    if self.amazon_price is None:
      self.amazon_price = other.amazon_price
    if self.uw_price is None:
      self.uw_price = other.uw_price


def MakePriceMap(lines, who):
  """ Returns a map of id -> Book. 'lines' should be an array of lines
  from a .dat file.
  """
  price_map = {}
  for line in lines:
    isbn, price = line.split()
    if price == 'None':
      price = None
    else:
      price = float(price)
    book = Book(isbn)
    if who == 'Amazon':
      book.amazon_price = price
    else:
      assert who == 'UW'
      book.uw_price = price
    price_map[book.id] = book
  return price_map

def main():
  amazon_prices = MakePriceMap(open(sys.argv[1], 'r').readlines(), 'Amazon')
  uw_prices = MakePriceMap(open(sys.argv[2], 'r').readlines(), 'UW')

  # Merge data from Amazon and UW.
  books = {}
  for i in amazon_prices:
    assert i in uw_prices
    book = amazon_prices[i]
    book.mergeFrom(uw_prices[i])
    books[i] = book

  books = list(books.values()) 
  
  # Filter books with missing data.
  books_before = len(books)
  books = [book for book in books if book.uw_price and book.amazon_price]
  print 'Filtered out %d books with missing data' % (books_before - len(books))

  # Filter books which have negative utility to us.
  books_before = len(books)
  books = [book for book in books if book.utility() > 1]
  print 'Filtered out %d unuseful books' % (books_before - len(books))

  # Sort by utility, descending.
  books.sort(key=lambda book: book.utility(), reverse=True)

  # Print CSV header.
  print 'ISBN, Profit, ROI'

  total_profit = 0
  total_investment = 0
  for book in books:
    total_profit += book.profit()
    total_investment += book.amazon_price
    print ('%s, %f, %f' % ( 
           book.isbn, book.profit(), book.roi()))

  print 'Total investment: $%.2f' % total_investment
  print 'Total profit: $%.2f' % total_profit

if __name__ == '__main__':
  main()

